package demo.jms;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

@Component("jmsSender")
public class JMSSender {
	
	@Autowired
	private JmsTemplate jmsTemplate;
	
	@Autowired
	private Queue queue;
	
	@Autowired
	private Topic topic;;
	
	public void start() {
		new Container(jmsTemplate, queue, topic).start();
	}

	public class Container extends Thread {
		private JmsTemplate jmsTemplate;
		private Queue queue;
		private Topic topic;
		
		public Container(JmsTemplate jmsTemplate, Queue queue, Topic topic) {
			this.jmsTemplate = jmsTemplate;
			this.queue = queue;
			this.topic = topic;
		}
		
		@Override
		public void run() {
			while(true) {
				System.out.println("Send message...");
				try {
					Thread.sleep(2000l);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				jmsTemplate.send(topic, new MessageCreator() {
					public Message createMessage(Session session) throws JMSException {
						TextMessage msg = session.createTextMessage();
						msg.setText("Hello World !");
						return msg;
					}
				});
			}
		}
		
	}
}
